/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun<iot25@lingyun>
 *                  All rights reserved.
 *
 *       Filename:  socket.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(24/04/25)
 *         Author:  LingYun <iot25@lingyun>
 *      ChangeLog:  1, Release initial version on "24/04/25 15:14:14"
 *                 
 ********************************************************************************/

#include "socket.h"

int init_client_context(client_ctx_t *ctx, char *server_ip, int server_port, int interval)
{
    if (!ctx || !server_ip) {
        return -1;
    }

    memset(ctx, 0, sizeof(client_ctx_t));
    strncpy(ctx->server_ip, server_ip, sizeof(ctx->server_ip) - 1);
    ctx->server_port = server_port;
    ctx->report_interval = interval;
    ctx->is_running = 1;
    ctx->sockfd = -1;
    ctx->db = NULL;

    return 0;
}



int connect_server(client_ctx_t *ctx)
{
    struct sockaddr_in servaddr;
    int rv;

    if (!ctx) {
        return -1;
    }

    // 创建套接字
    ctx->sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (ctx->sockfd < 0) {
        fprintf(stderr, "Create socket failure: %s\n", strerror(errno));
        return -1;
    }

    printf("Created socket[%d] successfully\n", ctx->sockfd);

    // 设置服务器地址
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(ctx->server_port);

    if (inet_pton(AF_INET, ctx->server_ip, &servaddr.sin_addr) <= 0) {
        fprintf(stderr, "Invalid address: %s\n", ctx->server_ip);
        close(ctx->sockfd);
        ctx->sockfd = -1;
        return -1;
    }

    // 连接服务器
    rv = connect(ctx->sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    if (rv < 0) {
        fprintf(stderr, "Connect to server[%s:%d] failure: %s\n",
                ctx->server_ip, ctx->server_port, strerror(errno));
        close(ctx->sockfd);
        ctx->sockfd = -1;
        return -1;
    }

    printf("Connected to server[%s:%d] successfully\n", ctx->server_ip, ctx->server_port);
    return 0;
}


